﻿$(function() {
    var grid = $("#grid").datagrid({
        title: "单项业务",
        iconCls: "icon-save",
        methord: "post",
        url: "/Main/GetList/",
        sortName: "ID",
        sortOrder: "desc",
        idField: "ID",
        pageSize: 20,
        striped: true, //奇偶行是否区分
		rowStyler: function(index,row){
					if (row.OwingMoney<0 && !row.Paidup && row.Verifier!=null && row.Verifier != ""){
						return "background-color:#EE3B3B;color:#fff;";
					}
				},
        frozenColumns: [[
	                { field: "ck", checkbox: true }
				]],
        columns: [[
					{ field: "BusinessCode", title: "编号" },
                    { field: "TheName", title: "客户名称", sortable:true},
					{field: "TaxNumber", title: "纳税人识别号"},
                    { field: "Phone", title: "电话"},
                    { field: "Contact", title: "联系人"},
                    { field: "TypeName", title: "项目名称"},
					{ field: "Charges", title: "合同金额"},
					{ field: "BeginDate", title: "合同开始日期", formatter: $.getJsonDate},
					{ field: "EndDate", title: "合同终止日期", formatter: $.getJsonDate},
					{ field: "Introducer", title: "客户介绍人", sortable:true},
					{ field: "Agent", title: "项目经办人", sortable:true},
					{ field: "OfficeName", title:"所属部室"},
					{ field: "DepartmentName", title: "所属分局"},
                    { field: "OwingMoney", title: "欠费", sortable:true, formatter: function (value, row, index) {
                        if(row.Verifier!=null && row.Verifier != "")
						{
						    if (value>=0) {
                                return "否";
					        }
							else
								return value;
						}
						else
							return "";
					    }
					},
					{ field: "BillDate", title: "开票日期", formatter: $.getJsonDate},
					{ field: "BillUnitName", title: "开票单位"},
					{ field: "FillIn", title:"填表人"},
					{ field: "Verifier", title:"审核"},
					{ field: "PaymentType", title:"类型", sortable:true},
					{ field: "Paidup", title:"缴清", hidden: true}

				]],
        fit: true,
        pagination: true,
        rownumbers: true,
        fitColumns: true,
        singleSelect: false,
        onDblClickRow: function (rowIndex, rowData) {  //双击事件
            $("<div></div>").dialog({
				title: "业务详情",
				modal: true,
				resizable: true,
				width: 900,
				height: 500,
				href: "/Main/ViewDetail?id="+rowData.ID,
				onClose:function(){  
                    $(this).dialog("destroy");
				},
				onLoad: function(){
					$("#viewForm").form("clear").form({
						"onLoadSuccess":function(data){
						var a = $("#OwingMoney").textbox("getText");
						if(a==""){
							$("#OwingMoney").textbox("setValue","0");  
						}
						$("#viewForm").find("#FoundDate").textbox("setValue",$.getJsonDate(data.FoundDate));
						$("#viewForm").find("#BeginDate").textbox("setValue",$.getJsonDate(data.BeginDate));
						$("#viewForm").find("#EndDate").textbox("setValue",$.getJsonDate(data.EndDate));
						$("#viewForm").find("#BillDate").textbox("setValue",$.getJsonDate(data.BillDate));
						$("#viewForm").find("#ChargingDate").textbox("setValue",$.getJsonDate(data.ChargingDate));
					}
					}).form("load", rowData);
				},
				onLoadError: function(data, status, error){
				if(data.status == "400")
					indexPage.reLogin();
			    }
			});
        },
		onLoadError: function(data, status, error){
				if(data.status == "400")
					indexPage.reLogin();
			}
    });
    $("body").layout();
});

var BusinessManage = {};
BusinessManage.addForm = $("#addForm");
BusinessManage.DataGridgetSelectedArr = function() {
    var ids = [];
    var rows = $("#grid").datagrid("getSelections");
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].ID);
    }
    return ids;
}
BusinessManage.DataGridgetSelectedID = function() {
    var ids = BusinessManage.DataGridgetSelectedArr.getSelectedArr();
    return ids.join(",");
}

BusinessManage.DataGridAdd = function() {
    $("#dlg").dialog({
		title: "添加业务信息",
		modal: true,
		resizable: true,
		buttons: "#dlg_btn",
		href: "/Main/CreateBusiness",
        onLoadError: function(data, status, error){
				if(data.status == "400")
					indexPage.reLogin();
		}		
	});
}

BusinessManage.DataGridEdit = function() {
	var rows = $("#grid").datagrid("getSelections");
    var num = rows.length;
    if (num == 0) {
        $.messager.alert("提示:","请选择一条记录进行操作!","info");
        return;
    }
    else if (num > 1) {
        $.messager.alert("提示","请选择一条记录进行修改!","info"); //$.messager.alert("提示", "您选择了多条记录,只能选择一条记录进行修改!", "info");
        return;
    }
    else {
		if(rows[0].Verifier=="" || rows[0].Verifier == null || $("#authID_DXYW").val()=="2"){
			//alert(rows[0].ProductId);
			//$("#updateForm").form("clear");
			$("#dlgEdit").dialog({
				title: "修改业务信息",
				modal: true,
				resizable: true,
				toolbar: [{
					text: "保存",
					iconCls: "icon-save",
					handler: function(){
						BusinessManage.UpdateFormSaveData();
					}
				}, "-", {
					text: "关闭",
					iconCls: "icon-no",
					handler: function () {
						$("#dlgEdit").dialog("close");
					}
				}],
				href: "/Main/UpdateBusiness",
				onLoad: function(){
					$("#updateForm").form({
						"onLoadSuccess":function(data){
							//$("#BeginDate").datebox("setValue",$.getJsonDate(data.BeginDate));
						    //$("#EndDate").datebox("setValue",$.getJsonDate(data.EndDate));						  
							$("#updateForm").find("#BeginDate").textbox("setValue",$.getJsonDate(data.BeginDate));
							$("#updateForm").find("#EndDate").textbox("setValue",$.getJsonDate(data.EndDate));
							$("#updateForm").find("#BillDate").textbox("setValue",$.getJsonDate(data.BillDate));
							$("#updateForm").find("#ChargingDate").textbox("setValue",$.getJsonDate(data.ChargingDate));
							if(data.Verifier!=null)
							{
								$("#checkedUpdate").show();
								$("#checkedPayUpdate").show();
								$("#checkedBillUpdate").show();
								$("#updateBill").val("1");
							}
							else{
								$("#checkedUpdate").hide();
                                $("#checkedPayUpdate").hide();
								$("#checkedBillUpdate").hide();
							}
					}
					}).form("load", rows[0]);
				},
                onLoadError: function(data, status, error){
				if(data.status == "400")
					indexPage.reLogin();
			    }
			});
		}
		else{
			$.messager.alert("提示","客户名称为"+rows[0].TheName+"的信息已经审核，无法修改。","info");
			return false;
		}
    }
}

BusinessManage.DataGridDel = function() {
    var ids = [];
    var rows = $("#grid").datagrid("getSelections");
    for (var i = 0; i < rows.length; i++) {
		if(rows[i].Verifier=="" || rows[i].Verifier == null || $("#authID_DXYW").val()=="2"){
			ids.push(rows[i].ID);
		}
		else{
			$.messager.alert("提示","客户名称为"+rows[i].TheName+"的信息已经审核，无法删除。","info");
			return false;
		}
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "您确认要删除选中的记录吗?", function (data) {
            if (data) {
                $.ajax({
                    url: "/main/DeleteBusiness?ids=" + ids.join(","),
                    type: "post",
                    success: function (re) {
                        var data = eval("(" + re + ")");
                        if (data.success) {
                            $.messager.alert("提示",ids.length + "条记录" + data.msg,"info"); //提示消息
                            $("#grid").datagrid("reload");
                            $("#grid").datagrid("clearSelections"); //清除所有选中的元素
                        } else {
                            $.messager.alert("错误", data.msg, "error");
                        }
                    },
					error: function(data, status, error){
						if(data.status == "400")
							indexPage.reLogin();
						else{
							$.messager.alert("错误", "删除失败!", "error");
                            $("#grid").datagrid("clearSelections");
						}
					}
                });
            }
        });
    } else {
        $.messager.alert("提示","请先选择要删除的记录。","info");

    }
}

BusinessManage.DataGridSearch = function(){
	var type1 = $("#cParent").combobox("getValue");
	var type2 = $("#cChildren").combobox("getValue");
	var customer = $("#cName").val();
	var showall = $("#showAll").is(':checked');
	$("#grid").datagrid({ url: "/Main/GetListByType", queryParams: { type1:type1, type2:type2, customer:customer, showall:showall } });
}

BusinessManage.DataGridCheck = function(){
	var rows = $("#grid").datagrid("getSelections");
    var num = rows.length;
    if (num == 0) {
        $.messager.alert("提示:","请选择一条记录进行操作!","info");
        return;
    }
    else if (num > 1) {
        $.messager.alert("提示","请选择一条记录进行操作!","info"); //$.messager.alert("提示", "您选择了多条记录,只能选择一条记录进行修改!", "info");
        return;
    }
    else {
		if(rows[0].Verifier=="" || rows[0].Verifier == null){
			//alert(rows[0].ProductId);
			//$("#updateForm").form("clear");
			$("#dlgCheck").dialog({
				title: "审核业务信息",
				modal: true,
				resizable: true,
				toolbar: [{
					text: "保存",
					iconCls: "icon-save",
					handler: function(){
						BusinessManage.CheckFormSaveData();
					}
				}, "-", {
					text: "关闭",
					iconCls: "icon-no",
					handler: function () {
						$("#dlgCheck").dialog("close");
					}
				}],
				width: 900,
				height: 500,
				href: "/Main/CheckBusiness",
				onLoad: function(){
					$("#checkForm").form({
						"onLoadSuccess":function(data){
						$("#BeginDate").datebox("setValue",$.getJsonDate(data.BeginDate));
						$("#EndDate").datebox("setValue",$.getJsonDate(data.EndDate));
					}
					}).form("load", rows[0]);
				},
				onLoadError: function(data, status, error){
				    if(data.status == "400")
					    indexPage.reLogin();
			    }
			});
		}
		else{
			$.messager.alert("提示","客户名称为"+rows[0].TheName+"的信息已经审核。","info");
			return false;
		}
    }
}

BusinessManage.DataGridCharging = function(){
	var rows = $("#grid").datagrid("getSelections");
    var num = rows.length;
    if (num == 0) {
        $.messager.alert("提示:","请选择一条记录进行操作!","info");
        return;
    }
    else if (num > 1) {
        $.messager.alert("提示","请选择一条记录进行操作!","info"); //$.messager.alert("提示", "您选择了多条记录,只能选择一条记录进行修改!", "info");
        return;
    }
    else {
		if(!rows[0].Paidup && rows[0].OwingMoney<0 && rows[0].Verifier != null && rows[0].Verifier != ""){
			//alert(rows[0].ProductId);
			//$("#updateForm").form("clear");
			$("#dlgCharging").dialog({
				title: "续缴费用",
				modal: true,
				resizable: true,
				toolbar: [{
					text: "保存",
					iconCls: "icon-save",
					handler: function(){
						BusinessManage.chargingFormSave();
					}
				}, "-", {
					text: "关闭",
					iconCls: "icon-no",
					handler: function () {
						$("#dlgCharging").dialog("close");
					}
				}],
				width: 900,
				height: 140,
				href: "/Main/ChargingMoney",
				onLoad: function(){
					$("#chargingForm").form("load", {ID:rows[0].ID, OwingMoney:rows[0].OwingMoney});
				},
				onLoadError: function(data, status, error){
				    if(data.status == "400")
					    indexPage.reLogin();
			    }
			});
		}
		else{
			$.messager.alert("提示","无法为客户"+rows[0].TheName+"续缴费用。","info");
			return false;
		}
    }
}

BusinessManage.DataGridBill = function(){
	var rows = $("#grid").datagrid("getSelections");
    var num = rows.length;
    if (num == 0) {
        $.messager.alert("提示:","请选择一条记录进行操作!","info");
        return;
    }
    else if (num > 1) {
        $.messager.alert("提示","请选择一条记录进行操作!","info"); //$.messager.alert("提示", "您选择了多条记录,只能选择一条记录进行修改!", "info");
        return;
    }
    else {
		if(rows[0].Verifier != null && rows[0].Verifier != "" && (rows[0].BillDate == null || rows[0].BillDate == "") ){
			$("#dlgBill").dialog({
				title: "补开发票",
				modal: true,
				resizable: true,
				toolbar: [{
					text: "保存",
					iconCls: "icon-save",
					handler: function(){
						BusinessManage.reBillFormSave();
					}
				}, "-", {
					text: "关闭",
					iconCls: "icon-no",
					handler: function () {
						$("#dlgBill").dialog("close");
					}
				}],
				width: 900,
				height: 140,
				href: "/Main/ReBill",
				onLoad: function(){
					$("#reBillForm").form("load", {ID:rows[0].ID});
				},
                onLoadError: function(data, status, error){
				    if(data.status == "400")
					    indexPage.reLogin();
			    }	
			});
		}
		else{
			$.messager.alert("提示","无法为客户"+rows[0].TheName+"补开发票。","info");
			return false;
		}
    }
}

BusinessManage.AddFormSaveData = function(){
    // $("#addForm").form("submit", {
        // url: "Main/SaveData",
        // onSubmit: function (param) {
			// param.FillInID = $("#UserID").val();
			// param.FillIn = $("#UserName").val();
			// param.TypeName1 = $("#BusinessType1").combobox("getText");
			// param.TypeName2 = $("#BusinessType2").combobox("getText");
            // return $(this).form("validate");
        // },
        // success: function(data){
			// var data = eval("(" + data + ")");
			// if (data.success){
				// $.messager.alert("提示",data.msg,"info");
				// $("#addForm").form("clear");
				// $("#grid").datagrid("reload");
			// }
			// else{
				// $.messager.alert("错误",data.msg,"error");
			// }
		// },
		// error: function(data, status, error){
			// if(data.status == "400")
				// $.messager.alert("重新登陆","info");
		// }
    // });
	if($("#addForm").form('validate'))
	{
		$.ajax({
            type: "POST",   //post提交方式默认是get
            url: "Main/SaveData",
            data: $("#addForm").serialize(),   //序列化               
            error: function (data, status, error) {      // 设置表单提交出错                 
                if(data.status == "400")
				    indexPage.reLogin();
            },
            success: function (data) {
                var msg = eval('(' + data + ')');
                if (msg.success) {
                    $.messager.alert("提示",msg.msg,"info");
					$("#addForm").form("clear");
				    $("#grid").datagrid("reload");
                }
                else {
                    $.messager.alert('错误', msg.msg, 'error');
                }
            }
        })
	}
}

BusinessManage.AddFormCancle = function(){
	$("#addForm").form("clear");
}

BusinessManage.DLGClose = function(){
	$("#dlg").dialog("close");
}

BusinessManage.UpdateFormSaveData = function(){
	if($("#updateForm").form('validate'))
	{
		$.ajax({
            type: "POST",   //post提交方式默认是get
            url: "Main/UpdateData",
            data: $("#updateForm").serialize(),   //序列化               
            error: function (data, status, error) {      // 设置表单提交出错                 
                if(data.status == "400")
				    indexPage.reLogin();
            },
            success: function (data) {
                var msg = eval('(' + data + ')');
                if (msg.success) {
                    $.messager.alert("提示",msg.msg,"info");
					$("#dlgEdit").dialog("close");
					$("#grid").datagrid("reload");
					$("#grid").datagrid("clearSelections");
                }
                else {
                    $.messager.alert('错误', msg.msg, 'error');
                }
            }
        })
	}
}

BusinessManage.CheckFormSaveData = function(){
	if($("#checkForm").form('validate'))
	{
		$.ajax({
            type: "POST",   //post提交方式默认是get
            url: "Main/SaveCheck",
            data: $("#checkForm").serialize(),   //序列化               
            error: function (data, status, error) {      // 设置表单提交出错                 
                if(data.status == "400")
				    indexPage.reLogin();
            },
            success: function (data) {
                var msg = eval('(' + data + ')');
                if (msg.success) {
                    $.messager.alert("提示",msg.msg,"info");
					$("#dlgCheck").dialog("close");
					$("#grid").datagrid("reload");
					$("#grid").datagrid("clearSelections");
                }
                else {
                    $.messager.alert('错误', msg.msg, 'error');
                }
            }
        })
	}
}

BusinessManage.chargingFormSave = function(){
	if($("#chargingForm").form('validate'))
	{
		$.ajax({
            type: "POST",   //post提交方式默认是get
            url: "Main/SaveCharging",
            data: $("#chargingForm").serialize(),   //序列化               
            error: function (data, status, error) {      // 设置表单提交出错                 
                if(data.status == "400")
				    indexPage.reLogin();
            },
            success: function (data) {
                var msg = eval('(' + data + ')');
                if (msg.success) {
                    $.messager.alert("提示",msg.msg,"info");
					$("#dlgCharging").dialog("close");
					$("#grid").datagrid("reload");
					$("#grid").datagrid("clearSelections");
                }
                else {
                    $.messager.alert('错误', msg.msg, 'error');
                }
            }
        })
	}
}

BusinessManage.reBillFormSave = function()
{
	if($("#reBillForm").form('validate'))
	{
		$.ajax({
            type: "POST",   //post提交方式默认是get
            url: "Main/SaveReBill",
            data: $("#reBillForm").serialize(),   //序列化               
            error: function (data, status, error) {      // 设置表单提交出错                 
                if(data.status == "400")
				    indexPage.reLogin();
            },
            success: function (data) {
                var msg = eval('(' + data + ')');
                if (msg.success) {
                    $.messager.alert("提示",msg.msg,"info");
					$("#dlgBill").dialog("close");
					$("#grid").datagrid("reload");
					$("#grid").datagrid("clearSelections");
                }
                else {
                    $.messager.alert('错误', msg.msg, 'error');
                }
            }
        })
	}
}

// function showAll() {
    // grid.datagrid({ url: virpath + "/Admin/LoadProductjson/" });
// }
function OpensearchWin() {
    searchWin.window("open");
    searchForm.form("clear");
    $("#Enable2").combobox("setValue", true); //默认设置开启搜素
}

function SearchOK() {
    var Name = $("#Name").val();
    var Id = $("#TypeId2").combobox("getValue");
    var bl = $("#Enable2").combobox("getValue"); //默认设置开启搜素
    var PId = $("#pid").val(); //ID
    var Price = $("#Price").val(); //价格
    //    alert(Name + "==" + Id + "==" + MId + "==" + bl + "==" + CId+"=="+Code);
    searchWin.window("close");
    grid.datagrid({ url: virpath + "/Admin/SeachProductInfo/", queryParams: { ProductName: Name, typeId: Id, ProductId: PId, RealPrice: Price, en: bl} });
    //经过测试queryParams参数可以提交到后台通过FormCollection获取 也可以Request["ProductName"]=?获取
}
function closeSearchWindow() {
    searchWin.window("close");
}